#!/bin/sh

. /usr/share/common

setup_ntp_from_dhcp() {
	echo "Use DHCP provided NTP servers: $ntpsrv"

	if [ -f "$NTP_WORKING_FILE" ] && [ '444' = "$(stat -c%a $NTP_WORKING_FILE)" ]; then
		echo "$NTP_WORKING_FILE is read-only, skipping update"
	else
		echo "Add DHCP provided NTP servers to $NTP_WORKING_FILE"
		echo $ntpsrv | tr ' ' '\n' | sed 's/^/server /; s/$/ iburst	#added by DHCP/' > $NTP_WORKING_FILE
	fi

	if [ -f "$TZNAME_FILE" ] && [ '444' = "$(stat -c%a $TZNAME_FILE)" ]; then
		echo "$TZNAME_FILE is read-only, skipping update"
	else
		if [ -n "$tzdbstr" ]; then
			if [ -f "$TZNAME_FILE" ] && [ "$(cat "$TZNAME_FILE")" == "$tzdbstr" ]; then
				echo "Timezone already set to '$tzdbstr', skipping update"
			else
				echo "Set timezone to '$tzdbstr' from DHCP"
				tzselect -n "${tzdbstr//\//\\\/}"
				echo "Rebooting to enforce the timezone"
				reboot -f
			fi
		fi
	fi
}

case "$1" in
	bound)
		[ -n "$ntpsrv" ] && setup_ntp_from_dhcp
		;;
	renew)
		[ -n "$ntpsrv" ] && setup_ntp_from_dhcp
		;;
esac

exit 0
